package cn.sell.mbg.sys.admin.service.impl;

import cn.sell.comm.base.MySqlCrudServiceImpl;
import cn.sell.comm.model.qo.PageQO;
import cn.sell.comm.model.vo.PageVO;
import cn.sell.comm.result.exceptions.DataNotFoundException;
import cn.sell.comm.util.DateUtil;
import cn.sell.mbg.sys.admin.SysAdmin;
import cn.sell.mbg.sys.admin.service.SysAdminService;
import cn.sell.mbg.sys.adminlog.SysAdminLoginLog;
import cn.sell.mbg.sys.adminlog.mapper.SysAdminLoginLogMapper;
import cn.sell.mbg.sys.adminlog.service.SysAdminLoginLogService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Log4j2
@Service
@Transactional
public class SysAdminServiceImpl extends MySqlCrudServiceImpl<SysAdmin, Long> implements SysAdminService {
    @Autowired
    SysAdminLoginLogService loginLogServiceImpl;
    @Autowired
    SysAdminLoginLogMapper loginLogMapper;

    @Override
    public SysAdmin getAdminByUsername(String username) {
        SysAdmin admin = new SysAdmin();
        admin.setUsername(username);
        admin.setStatus(1);
        List<SysAdmin> sysAdmins = super.selectByEntity(admin);
        if (null == sysAdmins) {
            return sysAdmins.get(0);
        }
        return null;
    }

    @Override
    public SysAdmin login(SysAdmin sysAdmin, HttpServletRequest request) {
        PageQO pageQO = new PageQO(1, 10);
        SysAdmin admin = new SysAdmin();
        admin.setUsername(sysAdmin.getUsername());
        admin.setPassword(sysAdmin.getPassword());
        admin.setStatus(1);
        pageQO.setCondition(admin);
        PageVO<SysAdmin> umsAdminPageVO = super.selectPage(pageQO);
        List<SysAdmin> list = umsAdminPageVO.getList();
//        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
//        SecurityContextHolder.getContext().setAuthentication(authentication);
//        token = jwtTokenUtil.generateToken(userDetails);
        if (null != list && list.size() == 1) {
            SysAdmin userAdmin = list.get(0);

            SysAdminLoginLog sysAdminLoginLog = new SysAdminLoginLog();
            sysAdminLoginLog.setIp(request.getRemoteAddr());
            sysAdminLoginLog.setAdminId(userAdmin.getId());
            sysAdminLoginLog.setCreateTime(DateUtil.formatDateTime(new Date(), DateUtil.DATETIME_DEFAULT_FORMAT));
            loginLogMapper.insert(sysAdminLoginLog);

            userAdmin.setLoginTime(DateUtil.formatDateTime(new Date(), DateUtil.DATETIME_DEFAULT_FORMAT));
            super.saveOrUpdate(userAdmin);
            return userAdmin;
        } else {
            throw new DataNotFoundException();
        }
    }
}
